package com.sos.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sos.exception.ErrorCode;
import com.sos.model.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    
    private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationEntryPoint.class);

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        // 对于/api/files/**路径，直接返回而不设置错误状态
        String requestURI = request.getRequestURI();
        logger.info("CustomAuthenticationEntryPoint处理请求URI: {}", requestURI);
        if (requestURI.startsWith("/api/files/")) {
            logger.info("跳过/api/files/路径的认证错误处理");
            // 让Spring MVC处理静态资源
            return;
        }
        
        // 关键：设置响应字符集为UTF-8
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name()); // 显式指定UTF-8
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        // 构建自定义响应
        ResultVO<?> result = ResultVO.error(ErrorCode.NOT_LOGIN.getCode(), ErrorCode.NOT_LOGIN.getMessage());
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}